<?php
namespace App\Admin\Controllers\ProductStockup;

use App\Importer\Basics\BImporter;
use App\Jobs\ProductStockup\StockupAreaSkuEstimateJob;
use App\Jobs\ProductStockup\StockupAreaSkuRatioJob;
use App\Models\Basics\SysArea;
use App\Models\Basics\Transport;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use App\Models\ProductStockup\Stockup;
use App\Models\SsBasic\StockupAreaClassifyEstimate;
use App\Models\SsBasic\StockupAreaSku;
use App\Models\SsBasic\StockupAreaSkuEstimate;
use App\Models\SsBasic\StockupAreaSkuRatio;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Illuminate\Support\Facades\DB;
class StockupUploadController extends AdminController{

    protected $title = '上传文件';

    protected function grid()
    {
        $type = request('type');
        return view("product-stockup.stockup.upload.index",compact('type'));
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $action = $request->get('action');
            $re = $this->{'_import'.$action}($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    /**
     * 创建基础备货产品（添加新产品）
     * @param UploadedFile $file
     * @return array|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    private function _importNewSku(UploadedFile $file){
        try{
            $data = Excel::toArray(new BImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $skuArr = [];
            $pCycle = [];
            $price = [];
            $transportDayArr = [];
            foreach($data as $row){
                $count++;
                $_area = $row[0] ? trim($row[0]) : '';
                $sku = $row[1] ? trim($row[1]) : '';
                if(!$_area || !$sku){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $area = strtoupper($_area);
                $key = $area.'_'.$sku;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $areaId = SysArea::getSysAreaIdByArea($area);
                if(!$areaId){
                    $errors[$count] = $_area.'系统不存在';
                    continue;
                }
                if(!array_key_exists($sku,$skuArr)){
                    $_pSku = ProductSku::getModelByCode($sku);
                    $skuArr[$sku] = $_pSku ?: false;
                }
                if(!$skuArr[$sku]){
                    $errors[$count] = $sku.'系统不存在';
                    continue;
                }
                $pSku = $skuArr[$sku];
                $areaSkuKey = $areaId.'_'.$pSku->id;
                $reCount = StockupAreaSku::query()->where('area_psku',$areaSkuKey)->count();
                if($reCount > 0){
                    $errors[$count] = $key.'系统已存在';
                    continue;
                }
                if(!array_key_exists($pSku->id,$price)){
                    $price[$pSku->id] = ProductSku::getPuPrice($pSku);
                }
                if(!array_key_exists($pSku->id,$pCycle)){
                    $pCycle[$pSku->id] = ProductSku::getPuCycle($pSku);
                }
                if(!array_key_exists($areaId,$transportDayArr)){
                    $_transportDay = Transport::getTransportDay($areaId);
                    $transportDayArr[$areaId] = $_transportDay ?: null;
                }
                $transportDay = $transportDayArr[$areaId];
                if($transportDay){
                    $airDay = $transportDay->air_day;
                    $seaDay = $transportDay->sea_day;
                }else{
                    $airDay = 0;
                    $seaDay = 0;
                }
                DB::beginTransaction();
                $areaSku = StockupAreaSku::query()->create(['area_psku' => $areaSkuKey,'type' => 2]);
                if(!$areaSku){
                    DB::rollBack();
                    continue;
                }

                ////备货总表
                //$stockup = $areaSku->stockup()->create([
                //        'area_id' => $areaId,
                //        'classify_id' => $pSku->classify_id,
                //        'psku_id' => $pSku->id,
                //        'unit_price' => $price[$pSku->id],
                //        'purchase_cycle' => $pCycle[$pSku->id],
                //        'air_day' => $airDay,
                //        'sea_day' => $seaDay,
                //    ]);
                //if(!$stockup){
                //    DB::rollBack();
                //}

                DB::commit();
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            DB::rollBack();
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    /**
     * 比例
     * @param UploadedFile $file
     * @return array|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    private function _importRatio(UploadedFile $file){
        try{
            $data = Excel::toArray(new BImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $item = [];

            foreach($data as $row){
                $count++;
                $_area = $row[0] ? trim($row[0]) : '';
                $sku = $row[1] ? trim($row[1]) : '';
                $_ratio = $row[2] ? trim($row[2]) : '';
                if(!$_area || !$sku){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $area = strtoupper($_area);
                $key = $area.'_'.$sku;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $areaId = SysArea::getSysAreaIdByArea($area);
                if(!$areaId){
                    $errors[$count] = $_area.'系统不存在';
                    continue;
                }
                $pSkuId = ProductSku::getValueByCode($sku,'id');
                if(!$pSkuId){
                    $errors[$count] = $sku.'系统不存在';
                    continue;
                }

                DB::beginTransaction();
                $areaSkuRatio = StockupAreaSkuRatio::query()->firstOrNew(['area_psku' => $areaId.'_'.$pSkuId]);
                $areaSkuRatio->area_id = $areaId;
                $areaSkuRatio->psku_id = $pSkuId;
                $areaSkuRatio->ratio = (float)$_ratio;

                $flag = $areaSkuRatio->save();
                if(!$flag){
                    DB::rollBack();
                }

                $item[] = $areaSkuRatio;
                DB::commit();
            }

            if(!empty($item)){
                StockupAreaSkuRatioJob::dispatch($item);
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    /**
     * 预估
     * @param UploadedFile $file
     * @return array|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    private function _importEstimate(UploadedFile $file){
        try{
            $data = Excel::toArray(new BImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $item = [];
            foreach($data as $row){
                $count++;
                $_area = $row[0] ? trim($row[0]) : '';
                $classify = $row[1] ? trim($row[1]) : '';
                $j = 2;
                for($i = 0; $i < StockupAreaSkuEstimate::NEW_ESTIMATE_NUM; $i++){
                    ${'estimate_num'.$i} = is_null($row[$j]) ? null : trim($row[$j]);
                    $j++;
                }
                if(!$_area || !$classify){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $area = strtoupper($_area);
                $key = $area.'_'.$classify;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $areaId = SysArea::getSysAreaIdByArea($area);
                if(!$areaId){
                    $errors[$count] = $_area.'系统不存在';
                    continue;
                }
                $classifyId = ProductClassify::getIdByTitle($classify);
                if(!$classifyId){
                    $errors[$count] = $classify.'系统不存在';
                    continue;
                }

                DB::beginTransaction();
                $areaClassifyEstimate = StockupAreaClassifyEstimate::query()->firstOrNew(['area_id' => $areaId,'classify_id' => $classifyId]);
                for($i = 0; $i < StockupAreaSkuEstimate::NEW_ESTIMATE_NUM; $i++){
                    if(!is_null(${'estimate_num'.$i})){
                        $areaClassifyEstimate->{'estimate_num'.$i} = ${'estimate_num'.$i};
                    }
                }

                if(!$areaClassifyEstimate->save()){
                    DB::rollBack();
                }

                $item[] = $areaClassifyEstimate;
                DB::commit();
            }
            if(!empty($item)){
                StockupAreaSkuEstimateJob::dispatch($item);
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            DB::rollBack();
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    /**
     * 需求（申请）
     * @param UploadedFile $file
     * @return array|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    private function _importApply(UploadedFile $file){

        try{
            $data = Excel::toArray(new BImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            DB::beginTransaction();
            $errors = [];
            $count = 1;
            $arr = [];
            $userId = Admin::user()->id;
            foreach($data as $row){
                $count++;
                $_area = $row[0] ? trim($row[0]) : '';
                $sku = $row[1] ? trim($row[1]) : '';
                $applyNum = $row[2] ? trim($row[2]) : 0;
                $applyRemark = $row[3] ? trim($row[3]) : '';
                if(!$_area || !$sku){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $area = strtoupper($_area);
                $key = $area.'_'.$sku;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                if(!is_numeric($applyNum)){
                    $errors[$count] = '备货数量格式有误';
                    continue;
                }
                if($applyNum < 0){
                    $errors[$count] = '备货数量不能小于0';
                    continue;
                }
                $areaId = SysArea::getSysAreaIdByArea($area);
                if(!$areaId){
                    $errors[$count] = $_area.'系统不存在';
                    continue;
                }
                $pSkuId = ProductSku::getValueByCode($sku,'id');
                if(!$pSkuId){
                    $errors[$count] = $sku.'系统不存在';
                    continue;
                }
                $stockup = Stockup::query()->where('area_id',$areaId)->where('psku_id',$pSkuId)->first();
                if(!$stockup){
                    $errors[$count] = $key.'系统不存在';
                    continue;
                }
                if($stockup->status >= 2){
                    $errors[$count] = $key.'已存在审批单据';
                    continue;
                }
                $stockup->apply_admin_id = $userId;
                $stockup->apply_num = $applyNum;
                $stockup->status = 1;
                if($applyRemark){
                    $stockup->apply_remark = $applyRemark;
                }
                $stockup->save();
            }
            DB::commit();
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            DB::rollBack();
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
